# Makefile for VCS compile-only flow (no TB required)
# Usage:
#  make sim                -> compile only (create simv)
#  make sim STUBS=stubs.txt-> generate stubs from stubs.txt then compile
#  make run                -> run ./simv (must exist)
#  make wave               -> run with waveform (vpd)
#  make clean              -> cleanup
VHDLAN      := vhdlan
VLOGAN      := vlogan
VHDL_ARGS   := -full64 -nc -work work
# Verilog/SystemVerilog compilation arguments
VLOG_ARGS   := -full64 -sverilog +v2k +lint=all,noSVA -timescale=1ns/1ps -work work
PROJECT_PATH := /home/zhengtk/OpenTPU/rtl# change this to your OpenTPU rtl root path
VCS      := vcs
VCS_ARGS := -full64 -sverilog +v2k +lint=all,noSVA -timescale=1ns/1ps -debug_all
SIMV     := ./simv
FILELIST := filelist.f
VHDL_FLIST  := vhdl_files.f
STUB_FILE:= tb/stubs.sv
STUBS    ?=                  # optionally pass list file: make sim STUBS=stubs.txt
PYGEN   := tools/gen_stubs.py

export PROJECT_PATH

.PHONY: all sim run wave clean gen_stubs

all: sim

# If user provided STUBS list, generate stubs first
gen_stubs:
	@if [ -n "$(STUBS)" ]; then \
	  echo "Generating stubs from $(STUBS) -> $(STUB_FILE)"; \
	  mkdir -p tb; \
	  python3 $(PYGEN) $(STUBS) $(STUB_FILE); \
	else \
	  echo "No STUBS specified (set STUBS=stubs.txt to auto-generate empty module stubs)"; \
	fi

# Step 1: Compile VHDL files using vhdlan
compile_vhdl:
	@echo "=== Step 1: Compiling VHDL files with vhdlan ==="
	$(VHDLAN) $(VHDL_ARGS) -f $(VHDL_FLIST) -l vhdlan.log
	@echo "=== VHDL compilation finished ==="

# Step 2: Compile Verilog/SystemVerilog files using vlogan
compile_vlog: compile_vhdl
	@echo "=== Step 2: Compiling Verilog/SystemVerilog files with vlogan ==="
	$(VLOGAN) $(VLOG_ARGS) -f $(FILELIST) -l vlogan.log
	@echo "=== Verilog compilation finished ==="

# Step 3: Link and elaborate using vcs
sim: gen_stubs compile_vlog
	@echo "=== Step 3: Linking with VCS ==="
	$(VCS) $(VCS_ARGS) -top $(TOP) -o $(SIMV) -l vcs.log || (echo "=== Link failed, see vcs.log ==="; false)
	@echo "=== Build finished: $(SIMV) created ==="


# Run sim (no waveform)
run: $(SIMV)
	@echo "=== Running simv ==="
	$(SIMV) +ntb_random_seed=1

# Run with waveform (vpd)
wave: $(SIMV)
	@echo "=== Running simv with vpd ==="
	$(SIMV) +ntb_random_seed=1 +vpdfile=sim.vpd

clean:
	@echo "=== Cleaning ==="
	rm -rf simv csrc ucli.key DVEfiles compile.log sim.vpd vcs.key tb/stubs.sv

# allow make sim without requiring simv explicit target
$(SIMV): sim